<!DOCTYPE html>


<html lang="en">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="小人物,码农" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    第八章 复用 |  歆雨小屋
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="歆雨小屋" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-第八章 复用"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  第八章 复用
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/07/29/%E7%AC%AC%E5%85%AB%E7%AB%A0%20%E5%A4%8D%E7%94%A8/" class="article-date">
  <time datetime="2020-07-29T14:26:31.000Z" itemprop="datePublished">2020-07-29</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/">Java编程思想</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">12.3k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">50 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <!-- Reuse -->

<blockquote>
<p>代码复用是面向对象编程（OOP）最具魅力的原因之一。</p>
</blockquote>
<p>对于像 C 语言等面向过程语言来说，“复用”通常指的就是“复制代码”。任何语言都可通过简单复制来达到代码复用的目的，但是这样做的效果并不好。Java 围绕“类”（Class）来解决问题。我们可以直接使用别人构建或调试过的代码，而非创建新类、重新开始。</p>
<p>如何在不污染源代码的前提下使用现存代码是需要技巧的。在本章里，你将学习到两种方式来达到这个目的：</p>
<ol>
<li><p>第一种方式直接了当。在新类中创建现有类的对象。这种方式叫做“组合”（Composition），通过这种方式复用代码的功能，而非其形式。</p>
</li>
<li><p>第二种方式更为微妙。创建现有类类型的新类。照字面理解：采用现有类形式，又无需在编码时改动其代码，这种方式就叫做“继承”（Inheritance），编译器会做大部分的工作。<strong>继承</strong>是面向对象编程（OOP）的重要基础之一。更多功能相关将在<a href="./09-Polymorphism.md">多态</a>（Polymorphism）章节中介绍。</p>
</li>
</ol>
<p>组合与继承的语法、行为上有许多相似的地方（这其实是有道理的，毕竟都是基于现有类型构建新的类型）。在本章中，你会学到这两种代码复用的方法。</p>
<a id="more"></a>
<!-- Composition Syntax -->

<h2 id="组合语法"><a href="#组合语法" class="headerlink" title="组合语法"></a>组合语法</h2><p>在前面的学习中，“组合”（Composition）已经被多次使用。你仅需要把对象的引用（object references）放置在一个新的类里，这就使用了组合。例如，假设你需要一个对象，其中内置了几个 <strong>String</strong> 对象，两个基本类型（primitives）的属性字段，一个其他类的对象。对于非基本类型对象，将引用直接放置在新类中，对于基本类型属性字段则仅进行声明。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/SprinklerSystem.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Composition for code reuse</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WaterSource</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String s;</span><br><span class="line">  WaterSource() &#123;</span><br><span class="line">    System.out.println(<span class="string">"WaterSource()"</span>);</span><br><span class="line">    s = <span class="string">"Constructed"</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> s; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SprinklerSystem</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String valve1, valve2, valve3, valve4;</span><br><span class="line">  <span class="keyword">private</span> WaterSource source = <span class="keyword">new</span> WaterSource();</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">int</span> i;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">float</span> f;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">      <span class="string">"valve1 = "</span> + valve1 + <span class="string">" "</span> +</span><br><span class="line">      <span class="string">"valve2 = "</span> + valve2 + <span class="string">" "</span> +</span><br><span class="line">      <span class="string">"valve3 = "</span> + valve3 + <span class="string">" "</span> +</span><br><span class="line">      <span class="string">"valve4 = "</span> + valve4 + <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"i = "</span> + i + <span class="string">" "</span> + <span class="string">"f = "</span> + f + <span class="string">" "</span> +</span><br><span class="line">      <span class="string">"source = "</span> + source; <span class="comment">// [1]</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    SprinklerSystem sprinklers = <span class="keyword">new</span> SprinklerSystem();</span><br><span class="line">    System.out.println(sprinklers);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">WaterSource()</span></span><br><span class="line"><span class="comment">valve1 = null valve2 = null valve3 = null valve4 = null</span></span><br><span class="line"><span class="comment">i = 0 f = 0.0 source = Constructed</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这两个类中定义的一个方法是特殊的:  <code>toString()</code>。每个非基本类型对象都有一个 <code>toString()</code> 方法，在编译器需要字符串但它有对象的特殊情况下调用该方法。因此，在 [1] 中，编译器看到你试图“添加”一个 <strong>WaterSource</strong> 类型的字符串对象 。因为字符串只能拼接另一个字符串，所以它就先会调用 <code>toString()</code> 将 <strong>source</strong> 转换成一个字符串。然后，它可以拼接这两个字符串并将结果字符串传递给 <code>System.out.println()</code>。要对创建的任何类允许这种行为，只需要编写一个 <strong>toString()</strong> 方法。在 <code>toString()</code> 上使用 <strong>@Override</strong> 注释来告诉编译器，以确保正确地覆盖。<strong>@Override</strong> 是可选的，但它有助于验证你没有拼写错误 (或者更微妙地说，大小写字母输入错误)。类中的基本类型字段自动初始化为零，正如 <strong>object Everywhere</strong> 一章中所述。但是对象引用被初始化为 <strong>null</strong>，如果你尝试调用其任何一个方法，你将得到一个异常（一个运行时错误）。方便的是，打印 <strong>null</strong> 引用却不会得到异常。</p>
<p>编译器不会为每个引用创建一个默认对象，这是有意义的，因为在许多情况下，这会导致不必要的开销。初始化引用有四种方法:</p>
<ol>
<li>当对象被定义时。这意味着它们总是在调用构造函数之前初始化。</li>
<li>在该类的构造函数中。</li>
<li>在实际使用对象之前。这通常称为<em>延迟初始化</em>。在对象创建开销大且不需要每次都创建对象的情况下，它可以减少开销。</li>
<li>使用实例初始化。</li>
</ol>
<p>以上四种实例创建的方法例子在这：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Bath.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Constructor initialization with composition</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Soap</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String s;</span><br><span class="line">  Soap() &#123;</span><br><span class="line">    System.out.println(<span class="string">"Soap()"</span>);</span><br><span class="line">    s = <span class="string">"Constructed"</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> s; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bath</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String <span class="comment">// Initializing at point of definition:</span></span><br><span class="line">    s1 = <span class="string">"Happy"</span>,</span><br><span class="line">    s2 = <span class="string">"Happy"</span>,</span><br><span class="line">    s3, s4;</span><br><span class="line">  <span class="keyword">private</span> Soap castille;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">int</span> i;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">float</span> toy;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">Bath</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"Inside Bath()"</span>);</span><br><span class="line">    s3 = <span class="string">"Joy"</span>;</span><br><span class="line">    toy = <span class="number">3.14f</span>;</span><br><span class="line">    castille = <span class="keyword">new</span> Soap();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Instance initialization:</span></span><br><span class="line">  &#123; i = <span class="number">47</span>; &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(s4 == <span class="keyword">null</span>) <span class="comment">// Delayed initialization:</span></span><br><span class="line">      s4 = <span class="string">"Joy"</span>;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">      <span class="string">"s1 = "</span> + s1 + <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"s2 = "</span> + s2 + <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"s3 = "</span> + s3 + <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"s4 = "</span> + s4 + <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"i = "</span> + i + <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"toy = "</span> + toy + <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"castille = "</span> + castille;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Bath b = <span class="keyword">new</span> Bath();</span><br><span class="line">    System.out.println(b);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">Inside Bath()</span></span><br><span class="line"><span class="comment">Soap()</span></span><br><span class="line"><span class="comment">s1 = Happy</span></span><br><span class="line"><span class="comment">s2 = Happy</span></span><br><span class="line"><span class="comment">s3 = Joy</span></span><br><span class="line"><span class="comment">s4 = Joy</span></span><br><span class="line"><span class="comment">i = 47</span></span><br><span class="line"><span class="comment">toy = 3.14</span></span><br><span class="line"><span class="comment">castille = Constructed</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>在 <strong>Bath</strong> 构造函数中，有一个代码块在所有初始化发生前就已经执行了。当你不在定义处初始化时，仍然不能保证在向对象引用发送消息之前执行任何初始化——如果你试图对未初始化的引用调用方法，则未初始化的引用将产生运行时异常。</p>
<p>当调用 <code>toString()</code> 时，它将赋值 s4，以便在使用字段的时候所有的属性都已被初始化。</p>
<!-- Inheritance Syntax -->

<h2 id="继承语法"><a href="#继承语法" class="headerlink" title="继承语法"></a>继承语法</h2><p>继承是所有面向对象语言的一个组成部分。事实证明，在创建类时总是要继承，因为除非显式地继承其他类，否则就隐式地继承 Java 的标准根类对象（Object）。</p>
<p>组合的语法很明显，但是继承使用了一种特殊的语法。当你继承时，你说，“这个新类与那个旧类类似。你可以在类主体的左大括号前的代码中声明这一点，使用关键字 <strong>extends</strong> 后跟基类的名称。当你这样做时，你将自动获得基类中的所有字段和方法。这里有一个例子:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Detergent.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Inheritance syntax &amp; properties</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Cleanser</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String s = <span class="string">"Cleanser"</span>;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">append</span><span class="params">(String a)</span> </span>&#123; s += a; &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">dilute</span><span class="params">()</span> </span>&#123; append(<span class="string">" dilute()"</span>); &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">apply</span><span class="params">()</span> </span>&#123; append(<span class="string">" apply()"</span>); &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">scrub</span><span class="params">()</span> </span>&#123; append(<span class="string">" scrub()"</span>); &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> s; &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Cleanser x = <span class="keyword">new</span> Cleanser();</span><br><span class="line">    x.dilute(); x.apply(); x.scrub();</span><br><span class="line">    System.out.println(x);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Detergent</span> <span class="keyword">extends</span> <span class="title">Cleanser</span> </span>&#123;</span><br><span class="line">  <span class="comment">// Change a method:</span></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">scrub</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    append(<span class="string">" Detergent.scrub()"</span>);</span><br><span class="line">    <span class="keyword">super</span>.scrub(); <span class="comment">// Call base-class version</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Add methods to the interface:</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">foam</span><span class="params">()</span> </span>&#123; append(<span class="string">" foam()"</span>); &#125;</span><br><span class="line">  <span class="comment">// Test the new class:</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Detergent x = <span class="keyword">new</span> Detergent();</span><br><span class="line">    x.dilute();</span><br><span class="line">    x.apply();</span><br><span class="line">    x.scrub();</span><br><span class="line">    x.foam();</span><br><span class="line">    System.out.println(x);</span><br><span class="line">    System.out.println(<span class="string">"Testing base class:"</span>);</span><br><span class="line">    Cleanser.main(args);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">Cleanser dilute() apply() Detergent.scrub() scrub()</span></span><br><span class="line"><span class="comment">foam()</span></span><br><span class="line"><span class="comment">Testing base class:</span></span><br><span class="line"><span class="comment">Cleanser dilute() apply() scrub()</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这演示了一些特性。首先，在 <strong>Cleanser</strong> 的 <code>append()</code> 方法中，使用 <code>+=</code> 操作符将字符串连接到 <strong>s</strong>，这是 Java 设计人员“重载”来处理字符串的操作符之一 (还有 + )。</p>
<p>第二，<strong>Cleanser</strong> 和 <strong>Detergent</strong> 都包含一个 <code>main()</code> 方法。你可以为每个类创建一个 <code>main()</code> ; 这允许对每个类进行简单的测试。当你完成测试时，不需要删除 <code>main()</code>; 你可以将其留在以后的测试中。即使程序中有很多类都有 <code>main()</code> 方法，惟一运行的只有在命令行上调用的 <code>main()</code>。这里，当你使用 <strong>java Detergent</strong> 时候，就调用了 <code>Detergent.main()</code>。但是你也可以使用 <strong>java Cleanser</strong> 来调用 <code>Cleanser.main()</code>，即使 <strong>Cleanser</strong> 不是一个公共类。即使类只具有包访问权，也可以访问 <code>public main()</code>。</p>
<p>在这里，<code>Detergent.main()</code> 显式地调用 <code>Cleanser.main()</code>，从命令行传递相同的参数(当然，你可以传递任何字符串数组)。</p>
<p><strong>Cleanser</strong> 中的所有方法都是公开的。请记住，如果不使用任何访问修饰符，则成员默认为包访问权限，这只允许包内成员访问。因此，如果没有访问修饰符，那么包内的任何人都可以使用这些方法。例如，<strong>Detergent</strong> 就没有问题。但是，如果其他包中的类继承 <strong>Cleanser</strong>，则该类只能访问 <strong>Cleanser</strong> 的公共成员。因此，为了允许继承，一般规则是所有字段为私有，所有方法为公共。(受保护成员也允许派生类访问;你以后会知道的。)在特定的情况下，你必须进行调整，但这是一个有用的指南。</p>
<p><strong>Cleanser</strong> 的接口中有一组方法: <code>append()</code>、<code>dilute()</code>、<code>apply()</code>、<code>scrub()</code> 和 <code>toString()</code>。因为 <strong>Detergent</strong> 是从 <strong>Cleanser</strong> 派生的(通过 <strong>extends</strong> 关键字)，所以它会在其接口中自动获取所有这些方法，即使你没有在 <strong>Detergent</strong> 中看到所有这些方法的显式定义。那么，可以把继承看作是复用类。如在 <code>scrub()</code> 中所见，可以使用基类中定义的方法并修改它。在这里，你可以在新类中调用基类的该方法。但是在 <code>scrub()</code> 内部，不能简单地调用 <code>scrub()</code>，因为这会产生递归调用。为了解决这个问题，Java的 <strong>super</strong> 关键字引用了当前类继承的“超类”(基类)。因此表达式 <code>super.scrub()</code> 调用方法 <code>scrub()</code> 的基类版本。</p>
<p>继承时，你不受限于使用基类的方法。你还可以像向类添加任何方法一样向派生类添加新方法:只需定义它。方法 <code>foam()</code> 就是一个例子。<code>Detergent.main()</code> 中可以看到，对于 <strong>Detergent</strong> 对象，你可以调用 <strong>Cleanser</strong> 和 <strong>Detergent</strong> 中可用的所有方法 (如 <code>foam()</code> )。</p>
<!-- Initializing the Base Class -->

<h3 id="初始化基类"><a href="#初始化基类" class="headerlink" title="初始化基类"></a>初始化基类</h3><p>现在涉及到两个类:基类和派生类。想象派生类生成的结果对象可能会让人感到困惑。从外部看，新类与基类具有相同的接口，可能还有一些额外的方法和字段。但是继承并不只是复制基类的接口。当你创建派生类的对象时，它包含基类的子对象。这个子对象与你自己创建基类的对象是一样的。只是从外部看，基类的子对象被包装在派生类的对象中。</p>
<p>必须正确初始化基类子对象，而且只有一种方法可以保证这一点 : 通过调用基类构造函数在构造函数中执行初始化，该构造函数具有执行基类初始化所需的所有适当信息和特权。Java 自动在派生类构造函数中插入对基类构造函数的调用。下面的例子展示了三个层次的继承:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Cartoon.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Constructor calls during inheritance</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Art</span> </span>&#123;</span><br><span class="line">  Art() &#123;</span><br><span class="line">    System.out.println(<span class="string">"Art constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Drawing</span> <span class="keyword">extends</span> <span class="title">Art</span> </span>&#123;</span><br><span class="line">  Drawing() &#123;</span><br><span class="line">    System.out.println(<span class="string">"Drawing constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cartoon</span> <span class="keyword">extends</span> <span class="title">Drawing</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">Cartoon</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"Cartoon constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Cartoon x = <span class="keyword">new</span> Cartoon();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">Art constructor</span></span><br><span class="line"><span class="comment">Drawing constructor</span></span><br><span class="line"><span class="comment">Cartoon constructor</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>构造从基类“向外”进行，因此基类在派生类构造函数能够访问它之前进行初始化。即使不为 <strong>Cartoon</strong> 创建构造函数，编译器也会为你合成一个无参数构造函数，调用基类构造函数。尝试删除 <strong>Cartoon</strong> 构造函数来查看这个。</p>
<!-- Constructors with Arguments -->

<h3 id="带参数的构造函数"><a href="#带参数的构造函数" class="headerlink" title="带参数的构造函数"></a>带参数的构造函数</h3><p>上面的所有例子中构造函数都是无参数的 ; 编译器很容易调用这些构造函数，因为不需要参数。如果没有无参数的基类构造函数，或者必须调用具有参数的基类构造函数，则必须使用 <strong>super</strong> 关键字和适当的参数列表显式地编写对基类构造函数的调用:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Chess.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Inheritance, constructors and arguments</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Game</span> </span>&#123;</span><br><span class="line">  Game(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    System.out.println(<span class="string">"Game constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BoardGame</span> <span class="keyword">extends</span> <span class="title">Game</span> </span>&#123;</span><br><span class="line">  BoardGame(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    <span class="keyword">super</span>(i);</span><br><span class="line">    System.out.println(<span class="string">"BoardGame constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chess</span> <span class="keyword">extends</span> <span class="title">BoardGame</span> </span>&#123;</span><br><span class="line">  Chess() &#123;</span><br><span class="line">    <span class="keyword">super</span>(<span class="number">11</span>);</span><br><span class="line">    System.out.println(<span class="string">"Chess constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Chess x = <span class="keyword">new</span> Chess();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">Game constructor</span></span><br><span class="line"><span class="comment">BoardGame constructor</span></span><br><span class="line"><span class="comment">Chess constructor</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>如果没有在 <strong>BoardGame</strong> 构造函数中调用基类构造函数，编译器就会报错找不到 <code>Game()</code> 的构造函数。此外，对基类构造函数的调用必须是派生类构造函数中的第一个操作。(如果你写错了，编译器会提醒你。)</p>
<!-- Delegation -->

<h2 id="委托"><a href="#委托" class="headerlink" title="委托"></a>委托</h2><p>Java不直接支持的第三种重用关系称为委托。这介于继承和组合之间，因为你将一个成员对象放在正在构建的类中(比如组合)，但同时又在新类中公开来自成员对象的所有方法(比如继承)。例如，宇宙飞船需要一个控制模块:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/SpaceShipControls.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpaceShipControls</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">up</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;&#125;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">down</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;&#125;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">left</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;&#125;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">right</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;&#125;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">forward</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;&#125;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">back</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;&#125;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">turboBoost</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>建造宇宙飞船的一种方法是使用继承:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/DerivedSpaceShip.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span></span></span><br><span class="line"><span class="class"><span class="title">DerivedSpaceShip</span> <span class="keyword">extends</span> <span class="title">SpaceShipControls</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String name;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">DerivedSpaceShip</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123; <span class="keyword">return</span> name; &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    DerivedSpaceShip protector =</span><br><span class="line">        <span class="keyword">new</span> DerivedSpaceShip(<span class="string">"NSEA Protector"</span>);</span><br><span class="line">    protector.forward(<span class="number">100</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然而， <strong>DerivedSpaceShip</strong> 并不是真正的“一种” <strong>SpaceShipControls</strong> ，即使你“告诉” <strong>DerivedSpaceShip</strong> 调用 <code>forward()</code>。更准确地说，一艘宇宙飞船包含了 <strong>SpaceShipControls *<em>，同时 *</em>SpaceShipControls</strong> 中的所有方法都暴露在宇宙飞船中。委托解决了这个难题:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/SpaceShipDelegation.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpaceShipDelegation</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> String name;</span><br><span class="line">  <span class="keyword">private</span> SpaceShipControls controls =</span><br><span class="line">    <span class="keyword">new</span> SpaceShipControls();</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">SpaceShipDelegation</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Delegated methods:</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">back</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;</span><br><span class="line">    controls.back(velocity);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">down</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;</span><br><span class="line">    controls.down(velocity);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">forward</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;</span><br><span class="line">    controls.forward(velocity);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">left</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;</span><br><span class="line">    controls.left(velocity);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">right</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;</span><br><span class="line">    controls.right(velocity);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">turboBoost</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    controls.turboBoost();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">up</span><span class="params">(<span class="keyword">int</span> velocity)</span> </span>&#123;</span><br><span class="line">    controls.up(velocity);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    SpaceShipDelegation protector =</span><br><span class="line">      <span class="keyword">new</span> SpaceShipDelegation(<span class="string">"NSEA Protector"</span>);</span><br><span class="line">    protector.forward(<span class="number">100</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法被转发到底层 <strong>control</strong> 对象，因此接口与继承的接口是相同的。但是，你对委托有更多的控制，因为你可以选择只在成员对象中提供方法的子集。</p>
<p>虽然Java语言不支持委托，但是开发工具常常支持。例如，上面的例子是使用 JetBrains Idea IDE 自动生成的。</p>
<!-- Combining Composition and Inheritance -->

<h2 id="结合组合与继承"><a href="#结合组合与继承" class="headerlink" title="结合组合与继承"></a>结合组合与继承</h2><p>你将经常同时使用组合和继承。下面的例子展示了使用继承和组合创建类，以及必要的构造函数初始化:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/PlaceSetting.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Combining composition &amp; inheritance</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Plate</span> </span>&#123;</span><br><span class="line">  Plate(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    System.out.println(<span class="string">"Plate constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DinnerPlate</span> <span class="keyword">extends</span> <span class="title">Plate</span> </span>&#123;</span><br><span class="line">  DinnerPlate(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    <span class="keyword">super</span>(i);</span><br><span class="line">    System.out.println(<span class="string">"DinnerPlate constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Utensil</span> </span>&#123;</span><br><span class="line">  Utensil(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    System.out.println(<span class="string">"Utensil constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Spoon</span> <span class="keyword">extends</span> <span class="title">Utensil</span> </span>&#123;</span><br><span class="line">  Spoon(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    <span class="keyword">super</span>(i);</span><br><span class="line">    System.out.println(<span class="string">"Spoon constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fork</span> <span class="keyword">extends</span> <span class="title">Utensil</span> </span>&#123;</span><br><span class="line">  Fork(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    <span class="keyword">super</span>(i);</span><br><span class="line">    System.out.println(<span class="string">"Fork constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Knife</span> <span class="keyword">extends</span> <span class="title">Utensil</span> </span>&#123;</span><br><span class="line">  Knife(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    <span class="keyword">super</span>(i);</span><br><span class="line">    System.out.println(<span class="string">"Knife constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// A cultural way of doing something:</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Custom</span> </span>&#123;</span><br><span class="line">  Custom(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    System.out.println(<span class="string">"Custom constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PlaceSetting</span> <span class="keyword">extends</span> <span class="title">Custom</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> Spoon sp;</span><br><span class="line">  <span class="keyword">private</span> Fork frk;</span><br><span class="line">  <span class="keyword">private</span> Knife kn;</span><br><span class="line">  <span class="keyword">private</span> DinnerPlate pl;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">PlaceSetting</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(i + <span class="number">1</span>);</span><br><span class="line">    sp = <span class="keyword">new</span> Spoon(i + <span class="number">2</span>);</span><br><span class="line">    frk = <span class="keyword">new</span> Fork(i + <span class="number">3</span>);</span><br><span class="line">    kn = <span class="keyword">new</span> Knife(i + <span class="number">4</span>);</span><br><span class="line">    pl = <span class="keyword">new</span> DinnerPlate(i + <span class="number">5</span>);</span><br><span class="line">    System.out.println(<span class="string">"PlaceSetting constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    PlaceSetting x = <span class="keyword">new</span> PlaceSetting(<span class="number">9</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">Custom constructor</span></span><br><span class="line"><span class="comment">Utensil constructor</span></span><br><span class="line"><span class="comment">Spoon constructor</span></span><br><span class="line"><span class="comment">Utensil constructor</span></span><br><span class="line"><span class="comment">Fork constructor</span></span><br><span class="line"><span class="comment">Utensil constructor</span></span><br><span class="line"><span class="comment">Knife constructor</span></span><br><span class="line"><span class="comment">Plate constructor</span></span><br><span class="line"><span class="comment">DinnerPlate constructor</span></span><br><span class="line"><span class="comment">PlaceSetting constructor</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>尽管编译器强制你初始化基类，并要求你在构造函数的开头就初始化基类，但它并不监视你以确保你初始化了成员对象。注意类是如何干净地分离的。你甚至不需要方法重用代码的源代码。你最多只导入一个包。(这对于继承和组合都是正确的。)</p>
<!-- Guaranteeing Proper Cleanup -->

<h3 id="保证适当的清理"><a href="#保证适当的清理" class="headerlink" title="保证适当的清理"></a>保证适当的清理</h3><p>Java 没有 C++ 中析构函数的概念，析构函数是在对象被销毁时自动调用的方法。原因可能是，在Java中，通常是忘掉而不是销毁对象，从而允许垃圾收集器根据需要回收内存。通常这是可以的，但是有时你的类可能在其生命周期中执行一些需要清理的活动。初始化和清理章节提到，你无法知道垃圾收集器何时会被调用，甚至它是否会被调用。因此，如果你想为类清理一些东西，必须显式地编写一个特殊的方法来完成它，并确保客户端程序员知道他们必须调用这个方法。最重要的是——正如在”异常”章节中描述的——你必须通过在 *<em>finally *</em>子句中放置此类清理来防止异常。</p>
<p>请考虑一个在屏幕上绘制图片的计算机辅助设计系统的例子:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/CADSystem.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Ensuring proper cleanup</span></span><br><span class="line"><span class="comment">// &#123;java reuse.CADSystem&#125;</span></span><br><span class="line"><span class="keyword">package</span> reuse;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line">  Shape(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    System.out.println(<span class="string">"Shape constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">dispose</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"Shape dispose"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Circle</span> <span class="keyword">extends</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line">  Circle(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    <span class="keyword">super</span>(i);</span><br><span class="line">    System.out.println(<span class="string">"Drawing Circle"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">dispose</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"Erasing Circle"</span>);</span><br><span class="line">    <span class="keyword">super</span>.dispose();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Triangle</span> <span class="keyword">extends</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line">  Triangle(<span class="keyword">int</span> i) &#123;</span><br><span class="line">    <span class="keyword">super</span>(i);</span><br><span class="line">    System.out.println(<span class="string">"Drawing Triangle"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">dispose</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"Erasing Triangle"</span>);</span><br><span class="line">    <span class="keyword">super</span>.dispose();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Line</span> <span class="keyword">extends</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="keyword">int</span> start, end;</span><br><span class="line">  Line(<span class="keyword">int</span> start, <span class="keyword">int</span> end) &#123;</span><br><span class="line">    <span class="keyword">super</span>(start);</span><br><span class="line">    <span class="keyword">this</span>.start = start;</span><br><span class="line">    <span class="keyword">this</span>.end = end;</span><br><span class="line">    System.out.println(</span><br><span class="line">      <span class="string">"Drawing Line: "</span> + start + <span class="string">", "</span> + end);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">dispose</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(</span><br><span class="line">      <span class="string">"Erasing Line: "</span> + start + <span class="string">", "</span> + end);</span><br><span class="line">    <span class="keyword">super</span>.dispose();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CADSystem</span> <span class="keyword">extends</span> <span class="title">Shape</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> Circle c;</span><br><span class="line">  <span class="keyword">private</span> Triangle t;</span><br><span class="line">  <span class="keyword">private</span> Line[] lines = <span class="keyword">new</span> Line[<span class="number">3</span>];</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">CADSystem</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(i + <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; lines.length; j++)</span><br><span class="line">      lines[j] = <span class="keyword">new</span> Line(j, j*j);</span><br><span class="line">    c = <span class="keyword">new</span> Circle(<span class="number">1</span>);</span><br><span class="line">    t = <span class="keyword">new</span> Triangle(<span class="number">1</span>);</span><br><span class="line">    System.out.println(<span class="string">"Combined constructor"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">dispose</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"CADSystem.dispose()"</span>);</span><br><span class="line">    <span class="comment">// The order of cleanup is the reverse</span></span><br><span class="line">    <span class="comment">// of the order of initialization:</span></span><br><span class="line">    t.dispose();</span><br><span class="line">    c.dispose();</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = lines.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--)</span><br><span class="line">      lines[i].dispose();</span><br><span class="line">    <span class="keyword">super</span>.dispose();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    CADSystem x = <span class="keyword">new</span> CADSystem(<span class="number">47</span>);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// Code and exception handling...</span></span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">      x.dispose();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">Shape constructor</span></span><br><span class="line"><span class="comment">Shape constructor</span></span><br><span class="line"><span class="comment">Drawing Line: 0, 0</span></span><br><span class="line"><span class="comment">Shape constructor</span></span><br><span class="line"><span class="comment">Drawing Line: 1, 1</span></span><br><span class="line"><span class="comment">Shape constructor</span></span><br><span class="line"><span class="comment">Drawing Line: 2, 4</span></span><br><span class="line"><span class="comment">Shape constructor</span></span><br><span class="line"><span class="comment">Drawing Circle</span></span><br><span class="line"><span class="comment">Shape constructor</span></span><br><span class="line"><span class="comment">Drawing Triangle</span></span><br><span class="line"><span class="comment">Combined constructor</span></span><br><span class="line"><span class="comment">CADSystem.dispose()</span></span><br><span class="line"><span class="comment">Erasing Triangle</span></span><br><span class="line"><span class="comment">Shape dispose</span></span><br><span class="line"><span class="comment">Erasing Circle</span></span><br><span class="line"><span class="comment">Shape dispose</span></span><br><span class="line"><span class="comment">Erasing Line: 2, 4</span></span><br><span class="line"><span class="comment">Shape dispose</span></span><br><span class="line"><span class="comment">Erasing Line: 1, 1</span></span><br><span class="line"><span class="comment">Shape dispose</span></span><br><span class="line"><span class="comment">Erasing Line: 0, 0</span></span><br><span class="line"><span class="comment">Shape dispose</span></span><br><span class="line"><span class="comment">Shape dispose</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>这个系统中的所有东西都是某种 <strong>Shape</strong> (它本身是一种 <strong>Object</strong>，因为它是从根类隐式继承的) 。除了使用 <strong>super</strong> 调用该方法的基类版本外，每个类还覆盖 <code>dispose()</code> 方法。特定的 <strong>Shape</strong> 类——<strong>Circle</strong>、<strong>Triangle</strong> 和 <strong>Line</strong>，都有 “draw” 构造函数，尽管在对象的生命周期中调用的任何方法都可以负责做一些需要清理的事情。每个类都有自己的 <code>dispose()</code> 方法来将非内存的内容恢复到对象存在之前的状态。</p>
<p>在 <code>main()</code> 中，有两个关键字是你以前没有见过的，在”异常”一章之前不会详细解释: <strong>try</strong> 和 <strong>finally</strong>。<strong>try</strong> 关键字表示后面的块 (用花括号分隔 )是一个受保护的区域，这意味着它得到了特殊处理。其中一个特殊处理是，无论 <strong>try</strong> 块如何退出，在这个保护区域之后的 <strong>finally</strong> 子句中的代码总是被执行。(通过异常处理，可以用许多不同寻常的方式留下 <strong>try</strong> 块。)这里，<strong>finally</strong> 子句的意思是，“无论发生什么，始终调用 <code>x.dispose()</code>。”</p>
<p>在清理方法 (在本例中是 <code>dispose()</code> ) 中，还必须注意基类和成员对象清理方法的调用顺序，以防一个子对象依赖于另一个子对象。首先，按与创建的相反顺序执行特定于类的所有清理工作。(一般来说，这要求基类元素仍然是可访问的。) 然后调用基类清理方法，如这所示。</p>
<p>在很多情况下，清理问题不是问题；你只需要让垃圾收集器来完成这项工作。但是，当你必须执行显式清理时，就需要多做努力，更加细心，因为在垃圾收集方面没有什么可以依赖的。可能永远不会调用垃圾收集器。如果调用，它可以按照它想要的任何顺序回收对象。除了内存回收外，你不能依赖垃圾收集来做任何事情。如果希望进行清理，可以使用自己的清理方法，不要使用 <code>finalize()</code>。</p>
<!-- Name Hiding -->

<h3 id="名称隐藏"><a href="#名称隐藏" class="headerlink" title="名称隐藏"></a>名称隐藏</h3><p>如果 Java 基类的方法名多次重载，则在派生类中重新定义该方法名不会隐藏任何基类版本。不管方法是在这个级别定义的，还是在基类中定义的，重载都会起作用:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Hide.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// Overloading a base-class method name in a derived</span></span><br><span class="line"><span class="comment">// class does not hide the base-class versions</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Homer</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">char</span> <span class="title">doh</span><span class="params">(<span class="keyword">char</span> c)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"doh(char)"</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'d'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="keyword">float</span> <span class="title">doh</span><span class="params">(<span class="keyword">float</span> f)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"doh(float)"</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">1.0f</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Milhouse</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bart</span> <span class="keyword">extends</span> <span class="title">Homer</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">doh</span><span class="params">(Milhouse m)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"doh(Milhouse)"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Hide</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Bart b = <span class="keyword">new</span> Bart();</span><br><span class="line">    b.doh(<span class="number">1</span>);</span><br><span class="line">    b.doh(<span class="string">'x'</span>);</span><br><span class="line">    b.doh(<span class="number">1.0f</span>);</span><br><span class="line">    b.doh(<span class="keyword">new</span> Milhouse());</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* Output:</span></span><br><span class="line"><span class="comment">doh(float)</span></span><br><span class="line"><span class="comment">doh(char)</span></span><br><span class="line"><span class="comment">doh(float)</span></span><br><span class="line"><span class="comment">doh(Milhouse)</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p><strong>Homer</strong> 的所有重载方法在 <strong>Bart</strong> 中都是可用的，尽管 <strong>Bart</strong> 引入了一种新的重载方法。在下一章中你将看到，使用与基类中完全相同的签名和返回类型覆盖相同名称的方法要常见得多。否则就会令人困惑。</p>
<p>你已经看到了Java 5 *<em>@Override *</em>注释，它不是关键字，但是可以像使用关键字一样使用它。当你打算重写一个方法时，你可以选择添加这个注释，如果你不小心用了重载而不是重写，编译器会产生一个错误消息:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Lisa.java</span></span><br><span class="line"><span class="comment">// (c)2017 MindView LLC: see Copyright.txt</span></span><br><span class="line"><span class="comment">// We make no guarantees that this code is fit for any purpose.</span></span><br><span class="line"><span class="comment">// Visit http://OnJava8.com for more book information.</span></span><br><span class="line"><span class="comment">// &#123;WillNotCompile&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Lisa</span> <span class="keyword">extends</span> <span class="title">Homer</span> </span>&#123;</span><br><span class="line">  <span class="meta">@Override</span> <span class="function"><span class="keyword">void</span> <span class="title">doh</span><span class="params">(Milhouse m)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"doh(Milhouse)"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>{WillNotCompile}</strong> 标记将该文件排除在本书的 <strong>Gradle</strong> 构建之外，但是如果你手工编译它，你将看到:方法不会覆盖超类中的方法， <strong>@Override</strong> 注释防止你意外地重载。</p>
<!-- Choosing Composition vs. Inheritance -->

<h2 id="组合与继承的选择"><a href="#组合与继承的选择" class="headerlink" title="组合与继承的选择"></a>组合与继承的选择</h2><p>组合和继承都允许在新类中放置子对象（组合是显式的，而继承是隐式的）。你或许想知道这二者之间的区别，以及怎样在二者间做选择。</p>
<p>当你想在新类中包含一个已有类的功能时，使用组合，而非继承。也就是说，在新类中嵌入一个对象（通常是私有的），以实现其功能。新类的使用者看到的是你所定义的新类的接口，而非嵌入对象的接口。</p>
<p>有时让类的用户直接访问到新类中的组合成分是有意义的。只需将成员对象声明为 <strong>public</strong> 即可（可以把这当作“半委托”的一种）。成员对象隐藏了具体实现，所以这是安全的。当用户知道你正在组装一组部件时，会使得接口更加容易理解。下面的 car 对象是个很好的例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Car.java</span></span><br><span class="line"><span class="comment">// Composition with public objects</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Engine</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">start</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rev</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stop</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Wheel</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">inflate</span><span class="params">(<span class="keyword">int</span> psi)</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Window</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rollup</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">rolldown</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Door</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> Window window = <span class="keyword">new</span> Window();</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">open</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Car</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> Engine engine = <span class="keyword">new</span> Engine();</span><br><span class="line">    <span class="keyword">public</span> Wheel[] wheel = <span class="keyword">new</span> Wheel[<span class="number">4</span>];</span><br><span class="line">    <span class="keyword">public</span> Door left = <span class="keyword">new</span> Door(), right = <span class="keyword">new</span> Door(); <span class="comment">// 2-door</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Car</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) &#123;</span><br><span class="line">            wheel[i] = <span class="keyword">new</span> Wheel();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Car car = <span class="keyword">new</span> Car();</span><br><span class="line">        car.left.window.rollup();</span><br><span class="line">        car.wheel[<span class="number">0</span>].inflate(<span class="number">72</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为在这个例子中 car 的组合也是问题分析的一部分（不是底层设计的部分），所以声明成员为 <strong>public</strong> 有助于客户端程序员理解如何使用类，且降低了类创建者面临的代码复杂度。但是，记住这是一个特例。通常来说，属性还是应该声明为 <strong>private</strong>。</p>
<p>当使用继承时，使用一个现有类并开发出它的新版本。通常这意味着使用一个通用类，并为了某个特殊需求将其特殊化。稍微思考下，你就会发现，用一个交通工具对象来组成一部车是毫无意义的——车不包含交通工具，它就是交通工具。这种“是一个”的关系是用继承来表达的，而“有一个“的关系则用组合来表达。</p>
<!-- protected -->

<h2 id="protected"><a href="#protected" class="headerlink" title="protected"></a>protected</h2><p>即然你已经接触到继承，关键字 <strong>protected</strong> 就变得有意义了。在理想世界中，仅靠关键字 <strong>private</strong> 就足够了。在实际项目中，却经常想把一个事物尽量对外界隐藏，而允许派生类的成员访问。</p>
<p>关键字 <strong>protected</strong> 就起这个作用。它表示“就类的用户而言，这是 <strong>private</strong> 的。但对于任何继承它的子类或在同一包中的类，它是可访问的。”（<strong>protected</strong> 也提供了包访问权限）</p>
<p>尽管可以创建 <strong>protected</strong> 属性，但是最好的方式是将属性声明为 <strong>private</strong> 以一直保留更改底层实现的权利。然后通过 <strong>protected</strong> 控制类的继承者的访问权限。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Orc.java</span></span><br><span class="line"><span class="comment">// The protected keyword</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Villain</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">set</span><span class="params">(String nm)</span> </span>&#123;</span><br><span class="line">        name = nm;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    Villain(String name) &#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"I'm a Villain and my name is "</span> + name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Orc</span> <span class="keyword">extends</span> <span class="title">Villain</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> orcNumber;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Orc</span><span class="params">(String name, <span class="keyword">int</span> orcNumber)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(name);</span><br><span class="line">        <span class="keyword">this</span>.orcNumber = orcNumber;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">change</span><span class="params">(String name, <span class="keyword">int</span> orcNumber)</span> </span>&#123;</span><br><span class="line">        set(name); <span class="comment">// Available because it's protected</span></span><br><span class="line">        <span class="keyword">this</span>.orcNumber = orcNumber;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"Orc "</span> + orcNumber + <span class="string">": "</span> + <span class="keyword">super</span>.toString();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Orc orc = <span class="keyword">new</span> Orc(<span class="string">"Limburger"</span>, <span class="number">12</span>);</span><br><span class="line">        System.out.println(orc);</span><br><span class="line">        orc.change(<span class="string">"Bob"</span>, <span class="number">19</span>);</span><br><span class="line">        System.out.println(orc);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Orc 12: I&#39;m a Villain and my name is Limburger</span><br><span class="line">Orc 19: I&#39;m a Villain and my name is Bob</span><br></pre></td></tr></table></figure>

<p><code>change()</code> 方法可以访问 <code>set()</code> 方法，因为 <code>set()</code> 方法是 <strong>protected</strong>。注意到，类 <strong>Orc</strong> 的  <code>toString()</code> 方法也使用了基类的版本。</p>
<!-- Upcasting -->
<h2 id="向上转型"><a href="#向上转型" class="headerlink" title="向上转型"></a>向上转型</h2><p>继承最重要的方面不是为新类提供方法。它是新类与基类的一种关系。简而言之，这种关系可以表述为“新类是已有类的一种类型”。</p>
<p>这种描述并非是解释继承的一种花哨方式，这是直接由语言支持的。例如，假设有一个基类 <strong>Instrument</strong> 代表音乐乐器和一个派生类 <strong>Wind</strong>。 因为继承保证了基类的所有方法在派生类中也是可用的，所以任意发送给该基类的消息也能发送给派生类。如果 <strong>Instrument</strong> 有一个 <code>play()</code> 方法，那么 <strong>Wind</strong> 也有该方法。这意味着你可以准确地说 <strong>Wind</strong> 对象也是一种类型的 <strong>Instrument</strong>。下面例子展示了编译器是如何支持这一概念的：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Wind.java</span></span><br><span class="line"><span class="comment">// Inheritance &amp; upcasting</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Instrument</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">play</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">tune</span><span class="params">(Instrument i)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">        i.play();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Wind objects are instruments</span></span><br><span class="line"><span class="comment">// because they have the same interface:</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Wind</span> <span class="keyword">extends</span> <span class="title">Instrument</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Wind flute = <span class="keyword">new</span> Wind();</span><br><span class="line">        Instrument.tune(flute); <span class="comment">// Upcasting</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>tune()</code> 方法接受了一个 <strong>Instrument</strong> 类型的引用。但是，在 <strong>Wind</strong> 的 <code>main()</code> 方法里，<code>tune()</code> 方法却传入了一个 <strong>Wind</strong> 引用。鉴于 Java 对类型检查十分严格，一个接收一种类型的方法接受了另一种类型看起来很奇怪，除非你意识到 <strong>Wind</strong> 对象同时也是一个 <strong>Instrument</strong> 对象，而且 <strong>Instrument</strong> 的 <code>tune</code> 方法一定会存在于 <strong>Wind</strong> 中。在 <code>tune()</code> 中，代码对 <strong>Instrument</strong> 和 所有 <strong>Instrument</strong> 的派生类起作用，这种把 <strong>Wind</strong> 引用转换为 <strong>Instrument</strong> 引用的行为称作<em>向上转型</em>。</p>
<p>该术语是基于传统的类继承图：图最上面是根，然后向下铺展。（当然你可以以任意方式画你认为有帮助的类图。）于是，<strong>Wind.java</strong> 的类图是：</p>
<p><img src="../images/1561774164644.png" alt="Wind 类图"></p>
<p>继承图中派生类转型为基类是向上的，所以通常称作<em>向上转型</em>。因为是从一个更具体的类转化为一个更一般的类，所以向上转型永远是安全的。也就是说，派生类是基类的一个超集。它可能比基类包含更多的方法，但它必须至少具有与基类一样的方法。在向上转型期间，类接口只可能失去方法，不会增加方法。这就是为什么编译器在没有任何明确转型或其他特殊标记的情况下，仍然允许向上转型的原因。</p>
<p>也可以执行与向上转型相反的向下转型，但是会有问题，对于该问题会放在下一章和“类型信息”一章进行更深入的探讨。</p>
<h3 id="再论组合和继承"><a href="#再论组合和继承" class="headerlink" title="再论组合和继承"></a>再论组合和继承</h3><p>在面向对象编程中，创建和使用代码最有可能的方法是将数据和方法一起打包到类中，然后使用该类的对象。也可以使用已有的类通过组合来创建新类。继承其实不太常用。因此尽管在教授 OOP 的过程中我们多次强调继承，但这并不意味着要尽可能使用它。恰恰相反，尽量少使用它，除非确实使用继承是有帮助的。一种判断使用组合还是继承的最清晰的方法是问一问自己是否需要把新类向上转型为基类。如果必须向上转型，那么继承就是必要的，但如果不需要，则要进一步考虑是否该采用继承。“多态”一章提出了一个使用向上转型的最有力的理由，但是只要记住问一问“我需要向上转型吗？”，就能在这两者中作出较好的选择。</p>
<!-- The final Keyword -->

<h2 id="final关键字"><a href="#final关键字" class="headerlink" title="final关键字"></a>final关键字</h2><p>根据上下文环境，Java 的关键字 <strong>final</strong> 的含义有些微的不同，但通常它指的是“这是不能被改变的”。防止改变有两个原因：设计或效率。因为这两个原因相差很远，所以有可能误用关键字 <strong>final</strong>。</p>
<p>以下几节讨论了可能使用 <strong>final</strong> 的三个地方：数据、方法和类。</p>
<h3 id="final-数据"><a href="#final-数据" class="headerlink" title="final 数据"></a>final 数据</h3><p>许多编程语言都有某种方法告诉编译器有一块数据是恒定不变的。恒定是有用的，如：</p>
<ol>
<li>一个永不改变的编译时常量。</li>
<li>一个在运行时初始化就不会改变的值。</li>
</ol>
<p>对于编译时常量这种情况，编译器可以把常量带入计算中；也就是说，可以在编译时计算，减少了一些运行时的负担。在 Java 中，这类常量必须是基本类型，而且用关键字 <strong>final</strong> 修饰。你必须在定义常量的时候进行赋值。</p>
<p>一个被 <strong>static</strong> 和 <strong>final</strong> 同时修饰的属性只会占用一段不能改变的存储空间。</p>
<p>当用 <strong>final</strong> 修饰对象引用而非基本类型时，其含义会有一点令人困惑。对于基本类型，<strong>final</strong> 使数值恒定不变，而对于对象引用，<strong>final</strong> 使引用恒定不变。一旦引用被初始化指向了某个对象，它就不能改为指向其他对象。但是，对象本身是可以修改的，Java 没有提供将任意对象设为常量的方法。（你可以自己编写类达到使对象恒定不变的效果）这一限制同样适用数组，数组也是对象。</p>
<p>下面例子展示了 <strong>final</strong> 属性的使用：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/FinalData.java</span></span><br><span class="line"><span class="comment">// The effect of final on fields</span></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Value</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i; <span class="comment">// package access</span></span><br><span class="line">    </span><br><span class="line">    Value(<span class="keyword">int</span> i) &#123;</span><br><span class="line">        <span class="keyword">this</span>.i = i;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FinalData</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Random rand = <span class="keyword">new</span> Random(<span class="number">47</span>);</span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">FinalData</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Can be compile-time constants:</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> valueOne = <span class="number">9</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> VALUE_TWO = <span class="number">99</span>;</span><br><span class="line">    <span class="comment">// Typical public constant:</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> VALUE_THREE = <span class="number">39</span>;</span><br><span class="line">    <span class="comment">// Cannot be compile-time constants:</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> i4 = rand.nextInt(<span class="number">20</span>);</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> INT_5 = rand.nextInt(<span class="number">20</span>);</span><br><span class="line">    <span class="keyword">private</span> Value v1 = <span class="keyword">new</span> Value(<span class="number">11</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Value v2 = <span class="keyword">new</span> Value(<span class="number">22</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Value VAL_3 = <span class="keyword">new</span> Value(<span class="number">33</span>);</span><br><span class="line">    <span class="comment">// Arrays:</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] a = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>&#125;;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id + <span class="string">": "</span> + <span class="string">"i4 = "</span> + i4 + <span class="string">", INT_5 = "</span> + INT_5;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        FinalData fd1 = <span class="keyword">new</span> FinalData(<span class="string">"fd1"</span>);</span><br><span class="line">        <span class="comment">//- fd1.valueOne++; // Error: can't change value</span></span><br><span class="line">        fd1.v2.i++; <span class="comment">// Object isn't constant</span></span><br><span class="line">        fd1.v1 = <span class="keyword">new</span> Value(<span class="number">9</span>); <span class="comment">// OK -- not final</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; fd1.a.length; i++) &#123;</span><br><span class="line">            fd1.a[i]++; <span class="comment">// Object isn't constant</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//- fd1.v2 = new Value(0); // Error: Can't</span></span><br><span class="line">        <span class="comment">//- fd1.VAL_3 = new Value(1); // change reference</span></span><br><span class="line">        <span class="comment">//- fd1.a = new int[3];</span></span><br><span class="line">        System.out.println(fd1);</span><br><span class="line">        System.out.println(<span class="string">"Creating new FinalData"</span>);</span><br><span class="line">        FinalData fd2 = <span class="keyword">new</span> FinalData(<span class="string">"fd2"</span>);</span><br><span class="line">        System.out.println(fd1);</span><br><span class="line">        System.out.println(fd2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">fd1: i4 &#x3D; 15, INT_5 &#x3D; 18</span><br><span class="line">Creating new FinalData</span><br><span class="line">fd1: i4 &#x3D; 15, INT_5 &#x3D; 18</span><br><span class="line">fd2: i4 &#x3D; 13, INT_5 &#x3D; 18</span><br></pre></td></tr></table></figure>

<p>因为 <strong>valueOne</strong> 和 <strong>VALUE_TWO</strong> 都是带有编译时值的 <strong>final</strong> 基本类型，它们都可用作编译时常量，没有多大区别。<strong>VALUE_THREE</strong> 是一种更加典型的常量定义的方式：<strong>public</strong> 意味着可以在包外访问，<strong>static</strong> 强调只有一个，<strong>final</strong> 说明是一个常量。</p>
<p>按照惯例，带有恒定初始值的 <strong>final</strong> <strong>static</strong> 基本变量（即编译时常量）命名全部使用大写，单词之间用下划线分隔。（源于 C 语言中定义常量的方式。）</p>
<p>我们不能因为某数据被 <strong>final</strong> 修饰就认为在编译时可以知道它的值。由上例中的 <strong>i4</strong> 和 <strong>INT_5</strong> 可以看出，它们在运行时才会赋值随机数。示例部分也展示了将 <strong>final</strong> 值定义为 <strong>static</strong> 和非 <strong>static</strong> 的区别。此区别只有当值在运行时被初始化时才会显现，因为编译器对编译时数值一视同仁。（而且编译时数值可能因优化而消失。）当运行程序时就能看到这个区别。注意到 <strong>fd1</strong> 和 <strong>fd2</strong> 的 <strong>i4</strong> 值不同，但 <strong>INT_5</strong> 的值并没有因为创建了第二个 <strong>FinalData</strong> 对象而改变，这是因为它是 <strong>static</strong> 的，在加载时已经被初始化，并不是每次创建新对象时都初始化。</p>
<p><strong>v1</strong> 到 <strong>VAL_3</strong> 变量说明了 <strong>final</strong> 引用的意义。正如你在 <code>main()</code> 中所见，<strong>v2</strong> 是 <strong>final</strong> 的并不意味着你不能修改它的值。因为它是引用，所以只是说明它不能指向一个新的对象。这对于数组具有同样的意义，数组只不过是另一种引用。（我不知道有什么方法能使数组引用本身成为 <strong>final</strong>。）看起来，声明引用为 <strong>final</strong> 没有声明基本类型 <strong>final</strong> 有用。</p>
<h3 id="空白-final"><a href="#空白-final" class="headerlink" title="空白 final"></a>空白 final</h3><p>空白 final 指的是没有初始化值的 <strong>final</strong> 属性。编译器确保空白 final 在使用前必须被初始化。这样既能使一个类的每个对象的 <strong>final</strong> 属性值不同，也能保持它的不变性。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/BlankFinal.java</span></span><br><span class="line"><span class="comment">// "Blank" final fields</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Poppet</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i;</span><br><span class="line">    </span><br><span class="line">    Poppet(<span class="keyword">int</span> ii) &#123;</span><br><span class="line">        i = ii;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BlankFinal</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> i = <span class="number">0</span>; <span class="comment">// Initialized final</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> j; <span class="comment">// Blank final</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Poppet p; <span class="comment">// Blank final reference</span></span><br><span class="line">    <span class="comment">// Blank finals MUST be initialized in constructor</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BlankFinal</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        j = <span class="number">1</span>; <span class="comment">// Initialize blank final</span></span><br><span class="line">        p = <span class="keyword">new</span> Poppet(<span class="number">1</span>); <span class="comment">// Init blank final reference</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BlankFinal</span><span class="params">(<span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">        j = x; <span class="comment">// Initialize blank final</span></span><br><span class="line">        p = <span class="keyword">new</span> Poppet(x); <span class="comment">// Init blank final reference</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> BlankFinal();</span><br><span class="line">        <span class="keyword">new</span> BlankFinal(<span class="number">47</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你必须在定义时或在每个构造器中执行 final 变量的赋值操作。这保证了 final 属性在使用前已经被初始化过。</p>
<h3 id="final-参数"><a href="#final-参数" class="headerlink" title="final 参数"></a>final 参数</h3><p>在参数列表中，将参数声明为 final 意味着在方法中不能改变参数指向的对象或基本变量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/FinalArguments.java</span></span><br><span class="line"><span class="comment">// Using "final" with method arguments</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Gizmo</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">spin</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FinalArguments</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">with</span><span class="params">(<span class="keyword">final</span> Gizmo g)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//-g = new Gizmo(); // Illegal -- g is final</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">without</span><span class="params">(Gizmo g)</span> </span>&#123;</span><br><span class="line">        g = <span class="keyword">new</span> Gizmo(); <span class="comment">// OK -- g is not final</span></span><br><span class="line">        g.spin();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//void f(final int i) &#123; i++; &#125; // Can't change</span></span><br><span class="line">    <span class="comment">// You can only read from a final primitive</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">g</span><span class="params">(<span class="keyword">final</span> <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> i + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        FinalArguments bf = <span class="keyword">new</span> FinalArguments();</span><br><span class="line">        bf.without(<span class="keyword">null</span>);</span><br><span class="line">        bf.with(<span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法 <code>f()</code> 和 <code>g()</code> 展示了 <strong>final</strong> 基本类型参数的使用情况。你只能读取而不能修改参数。这个特性主要用于传递数据给匿名内部类。这将在”内部类“章节中详解。</p>
<h3 id="final-方法"><a href="#final-方法" class="headerlink" title="final 方法"></a>final 方法</h3><p>使用 <strong>final</strong> 方法的原因有两个。第一个原因是给方法上锁，防止子类通过覆写改变方法的行为。这是出于继承的考虑，确保方法的行为不会因继承而改变。</p>
<p>过去建议使用 <strong>final</strong> 方法的第二个原因是效率。在早期的 Java 实现中，如果将一个方法指明为 <strong>final</strong>，就是同意编译器把对该方法的调用转化为内嵌调用。当编译器遇到 <strong>final</strong> 方法的调用时，就会很小心地跳过普通的插入代码以执行方法的调用机制（将参数压栈，跳至方法代码处执行，然后跳回并清理栈中的参数，最终处理返回值），而用方法体内实际代码的副本替代方法调用。这消除了方法调用的开销。但是如果一个方法很大代码膨胀，你也许就看不到内嵌带来的性能提升，因为内嵌调用带来的性能提高被花费在方法里的时间抵消了。</p>
<p>在最近的 Java 版本中，虚拟机可以探测到这些情况（尤其是 <em>hotspot</em> 技术），并优化去掉这些效率反而降低的内嵌调用方法。有很长一段时间，使用 <strong>final</strong> 来提高效率都被阻止。你应该让编译器和 JVM 处理性能问题，只有在为了明确禁止覆写方法时才使用 <strong>final</strong>。</p>
<h3 id="final-和-private"><a href="#final-和-private" class="headerlink" title="final 和 private"></a>final 和 private</h3><p>类中所有的 <strong>private</strong> 方法都隐式地指定为 <strong>final</strong>。因为不能访问 <strong>private</strong> 方法，所以不能覆写它。可以给 <strong>private</strong> 方法添加 <strong>final</strong> 修饰，但是并不能给方法带来额外的含义。</p>
<p>以下情况会令人困惑，当你试图覆写一个 <strong>private</strong> 方法（隐式是 <strong>final</strong> 的）时，看上去奏效，而且编译器不会给出错误信息：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/FinalOverridingIllusion.java</span></span><br><span class="line"><span class="comment">// It only looks like you can override</span></span><br><span class="line"><span class="comment">// a private or private final method</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WithFinals</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Identical to "private" alone:</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"WithFinals.f()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Also automatically "final":</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">g</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"WithFinals.g()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OverridingPrivate</span> <span class="keyword">extends</span> <span class="title">WithFinals</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"OverridingPrivate.f()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">g</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"OverridingPrivate.g()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">OverridingPrivate2</span> <span class="keyword">extends</span> <span class="title">OverridingPrivate</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"OverridingPrivate2.f()"</span>);</span><br><span class="line">    &#125; </span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">g</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"OverridingPrivate2.g()"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FinalOverridingIllusion</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        OverridingPrivate2 op2 = <span class="keyword">new</span> OverridingPrivate2();</span><br><span class="line">        op2.f();</span><br><span class="line">        op2.g();</span><br><span class="line">        <span class="comment">// You can upcast:</span></span><br><span class="line">        OverridingPrivate op = op2;</span><br><span class="line">        <span class="comment">// But you can't call the methods:</span></span><br><span class="line">        <span class="comment">//- op.f();</span></span><br><span class="line">        <span class="comment">//- op.g();</span></span><br><span class="line">        <span class="comment">// Same here:</span></span><br><span class="line">        WithFinals wf = op2;</span><br><span class="line">        <span class="comment">//- wf.f();</span></span><br><span class="line">        <span class="comment">//- wf.g();</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">OverridingPrivate2.f()</span><br><span class="line">OverridingPrivate2.g()</span><br></pre></td></tr></table></figure>

<p>“覆写”只发生在方法是基类的接口时。也就是说，必须能将一个对象向上转型为基类并调用相同的方法（这一点在下一章阐明）。如果一个方法是 <strong>private</strong> 的，它就不是基类接口的一部分。它只是隐藏在类内部的代码，且恰好有相同的命名而已。但是如果你在派生类中以相同的命名创建了 <strong>public</strong>，<strong>protected</strong> 或包访问权限的方法，这些方法与基类中的方法没有联系，你没有覆写方法，只是在创建新的方法而已。由于 <strong>private</strong> 方法无法触及且能有效隐藏，除了把它看作类中的一部分，其他任何事物都不需要考虑到它。</p>
<h3 id="final-类"><a href="#final-类" class="headerlink" title="final 类"></a>final 类</h3><p>当说一个类是 <strong>final</strong> （<strong>final</strong> 关键字在类定义之前），就意味着它不能被继承。之所以这么做，是因为类的设计就是永远不需要改动，或者是出于安全考虑不希望它有子类。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Jurassic.java</span></span><br><span class="line"><span class="comment">// Making an entire class final</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SmallBrain</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Dinosaur</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">7</span>;</span><br><span class="line">    <span class="keyword">int</span> j = <span class="number">1</span>;</span><br><span class="line">    SmallBrain x = <span class="keyword">new</span> SmallBrain();</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//- class Further extends Dinosaur &#123;&#125;</span></span><br><span class="line"><span class="comment">// error: Cannot extend final class 'Dinosaur'</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Jurassic</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Dinosaur n = <span class="keyword">new</span> Dinosaur();</span><br><span class="line">        n.f();</span><br><span class="line">        n.i = <span class="number">40</span>;</span><br><span class="line">        n.j++;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>final</strong> 类的属性可以根据个人选择是或不是 <strong>final</strong>。这同样适用于不管类是否是 <strong>final</strong> 的内部 <strong>final</strong> 属性。然而，由于 <strong>final</strong> 类禁止继承，类中所有的方法都被隐式地指定为 <strong>final</strong>，所以没有办法覆写它们。你可以在 final 类中的方法加上 <strong>final</strong> 修饰符，但不会增加任何意义。</p>
<h3 id="final-忠告"><a href="#final-忠告" class="headerlink" title="final 忠告"></a>final 忠告</h3><p>在设计类时将一个方法指明为 final 看上去是明智的。你可能会觉得没人会覆写那个方法。有时这是对的。</p>
<p>但请留意你的假设。通常来说，预见一个类如何被复用是很困难的，特别是通用类。如果将一个方法指定为 <strong>final</strong>，可能会防止其他程序员的项目中通过继承来复用你的类，而这仅仅是因为你没有想到它被以那种方式使用。</p>
<p>Java 标准类库就是一个很好的例子。尤其是 Java 1.0/1.1 的 <strong>Vector</strong> 类被广泛地使用，而且从效率考虑（这近乎是个幻想），如果它的所有方法没有被指定为 <strong>final</strong>，可能会更加有用。很容易想到，你可能会继承并覆写这么一个基础类，但是设计者们认为这么做不合适。有两个讽刺的原因。第一，<strong>Stack</strong> 继承自 <strong>Vector</strong>，就是说 <strong>Stack</strong> 是个 <strong>Vector</strong>，但从逻辑上来说不对。尽管如此，Java 设计者们仍然这么做，在用这种方式创建 <strong>Stack</strong> 时，他们应该意识到了 <strong>final</strong> 方法过于约束。</p>
<p>第二，<strong>Vector</strong> 中的很多重要方法，比如 <code>addElement()</code> 和 <code>elementAt()</code> 方法都是同步的。在“并发编程”一章中会看同步会导致很大的执行开销，可能会抹煞 <strong>final</strong> 带来的好处。这加强了程序员永远无法正确猜到优化应该发生在何处的观点。如此笨拙的设计却出现在每个人都要使用的标准库中，太糟糕了。庆幸的是，现代 Java 容器用 <strong>ArrayList</strong> 代替了 <strong>Vector</strong>，它的行为要合理得多。不幸的是，仍然有很多新代码使用旧的集合类库，其中就包括 <strong>Vector</strong>。</p>
<p>Java 1.0/1.1 标准类库中另一个重要的类是 <strong>Hashtable</strong>（后来被 <strong>HashMap</strong> 取代），它不含任何 <strong>final</strong> 方法。本书中其他地方也提到，很明显不同的类是由不同的人设计的。<strong>Hashtable</strong> 就比 <strong>Vector</strong> 中的方法名简洁得多，这又是一条证据。对于类库的使用者来说，这是一个本不应该如此草率的事情。这种不规则的情况造成用户需要做更多的工作——这是对粗糙的设计和代码的又一讽刺。</p>
<!-- Initialization and Class Loading -->

<h2 id="类初始化和加载"><a href="#类初始化和加载" class="headerlink" title="类初始化和加载"></a>类初始化和加载</h2><p>在许多传统语言中，程序在启动时一次性全部加载。接着初始化，然后程序开始运行。必须仔细控制这些语言的初始化过程，以确保 <strong>statics</strong> 初始化的顺序不会造成麻烦。在 C++ 中，如果一个 <strong>static</strong> 期望使用另一个 <strong>static</strong>，而另一个 <strong>static</strong> 还没有初始化，就会出现问题。</p>
<p>Java 中不存在这样的问题，因为它采用了一种不同的方式加载。因为 Java 中万物皆对象，所以加载活动就容易得多。记住每个类的编译代码都存在于它自己独立的文件中。该文件只有在使用程序代码时才会被加载。一般可以说“类的代码在首次使用时加载“。这通常是指创建类的第一个对象，或者是访问了类的 <strong>static</strong> 属性或方法。构造器也是一个 <strong>static</strong> 方法尽管它的 <strong>static</strong> 关键字是隐式的。因此，准确地说，一个类当它任意一个 <strong>static</strong> 成员被访问时，就会被加载。</p>
<p>首次使用时就是 <strong>static</strong> 初始化发生时。所有的 <strong>static</strong> 对象和 <strong>static</strong> 代码块在加载时按照文本的顺序（在类中定义的顺序）依次初始化。<strong>static</strong> 变量只被初始化一次。</p>
<h3 id="继承和初始化"><a href="#继承和初始化" class="headerlink" title="继承和初始化"></a>继承和初始化</h3><p>了解包括继承在内的整个初始化过程是有帮助的，这样可以对所发生的一切有全局性的把握。考虑下面的例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// reuse/Beetle.java</span></span><br><span class="line"><span class="comment">// The full process of initialization</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Insect</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i = <span class="number">9</span>;</span><br><span class="line">    <span class="keyword">protected</span> <span class="keyword">int</span> j;</span><br><span class="line">    </span><br><span class="line">    Insect() &#123;</span><br><span class="line">        System.out.println(<span class="string">"i = "</span> + i + <span class="string">", j = "</span> + j);</span><br><span class="line">        j = <span class="number">39</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> x1 = printInit(<span class="string">"static Insect.x1 initialized"</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">printInit</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        System.out.println(s);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">47</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Beetle</span> <span class="keyword">extends</span> <span class="title">Insect</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> k = printInit(<span class="string">"Beetle.k.initialized"</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Beetle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"k = "</span> + k);</span><br><span class="line">        System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> x2 = printInit(<span class="string">"static Beetle.x2 initialized"</span>);</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Beetle constructor"</span>);</span><br><span class="line">        Beetle b = <span class="keyword">new</span> Beetle();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">static Insect.x1 initialized</span><br><span class="line">static Beetle.x2 initialized</span><br><span class="line">Beetle constructor</span><br><span class="line">i &#x3D; 9, j &#x3D; 0</span><br><span class="line">Beetle.k initialized</span><br><span class="line">k &#x3D; 47</span><br><span class="line">j &#x3D; 39</span><br></pre></td></tr></table></figure>

<p>当执行 <strong>java Beetle</strong>，首先会试图访问 <strong>Beetle</strong> 类的 <code>main()</code> 方法（一个静态方法），加载器启动并找出 <strong>Beetle</strong> 类的编译代码（在名为 <strong>Beetle.class</strong> 的文件中）。在加载过程中，编译器注意到有一个基类，于是继续加载基类。不论是否创建了基类的对象，基类都会被加载。（可以尝试把创建基类对象的代码注释掉证明这点。）</p>
<p>如果基类还存在自身的基类，那么第二个基类也将被加载，以此类推。接下来，根基类（例子中根基类是 <strong>Insect</strong>）的 <strong>static</strong> 的初始化开始执行，接着是派生类，以此类推。这点很重要，因为派生类中 <strong>static</strong> 的初始化可能依赖基类成员是否被正确地初始化。</p>
<p>至此，必要的类都加载完毕，可以创建对象了。首先，对象中的所有基本类型变量都被置为默认值，对象引用被设为 <strong>null</strong> —— 这是通过将对象内存设为二进制零值一举生成的。接着会调用基类的构造器。本例中是自动调用的，但是你也可以使用 <strong>super</strong> 调用指定的基类构造器（在 <strong>Beetle</strong> 构造器中的第一步操作）。基类构造器和派生类构造器一样以相同的顺序经历相同的过程。当基类构造器完成后，实例变量按文本顺序初始化。最终，构造器的剩余部分被执行。</p>
<!-- Summary -->

<h2 id="本章小结"><a href="#本章小结" class="headerlink" title="本章小结"></a>本章小结</h2><p>继承和组合都是从已有类型创建新类型。组合将已有类型作为新类型底层实现的一部分，继承复用的是接口。</p>
<p>使用继承时，派生类具有基类接口，因此可以向上转型为基类，这对于多态至关重要，在下一章你将看到。</p>
<p>尽管在面向对象编程时极力强调继承，但在开始设计时，优先使用组合（或委托），只有当确实需要时再使用继承。组合更具灵活性。另外，通过对成员类型使用继承的技巧，可以在运行时改变成员的类型和行为。因此，可以在运行时改变组合对象的行为。</p>
<p>在设计一个系统时，目标是发现或创建一系列类，每个类有特定的用途，而且既不应太大（包括太多功能难以复用），也不应太小（不添加其他功能就无法使用）。如果设计变得过于复杂，通过将现有类拆分为更小的部分而添加更多的对象，通常是有帮助的。</p>
<p>当开始设计一个系统时，记住程序开发是一个增量过程，正如人类学习。它依赖实验，你可以尽可能多做分析，然而在项目开始时仍然无法知道所有的答案。如果把项目视作一个有机的，进化着的生命去培养，而不是视为像摩天大楼一样快速见效，就能获得更多的成功和更迅速的反馈。继承和组合正是可以让你执行如此实验的面向对象编程中最基本的两个工具。</p>
<!-- 分页 -->

<div style="page-break-after: always;"></div>

 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://yoursite.com/2020/07/29/%E7%AC%AC%E5%85%AB%E7%AB%A0%20%E5%A4%8D%E7%94%A8/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/" rel="tag">Java编程思想</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/OnJava8/" rel="tag">OnJava8</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/07/30/%E7%AC%AC%E4%B9%9D%E7%AB%A0%20%E5%A4%9A%E6%80%81/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            第九章 多态
          
        </div>
      </a>
    
    
      <a href="/2020/07/28/%E7%AC%AC%E4%B8%83%E7%AB%A0%20%E5%B0%81%E8%A3%85/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">第七章 封装</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> Gghui
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="歆雨小屋"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=371362&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
  </div>
</body>

</html>